package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceSrevice;
import com.sky.vo.*;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServicelmpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkSpaceSrevice workSpaceSrevice;
    /**
     * 数据统计相关接口（统计指定区间内的数据）
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存储begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //dateList.add(begin.plusDays(1));//plusDays(1)  : +1天
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }


        List<Double> list = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date对应的营业额，指状态为已完成的订单的金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);  //一天中的最小点
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);   //一天中的最大点
            Map map =new HashMap<>();
            map.put("status",Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endTime);
            Double turnover= orderMapper.selectStatus(map);
           turnover= turnover == null?0.0:turnover;
            list.add(turnover);
        }

        //把dateList里的每个元素之间用逗号分隔
        //StringUtils.join(dateList,",");
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(list,","))
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天新增用户数量  select count(id) from user where create_time<? and  create_time>?
        List<Integer> newUserList =new ArrayList<>();
        //存放每天总用户数量  select count(id) from where create_time<?
        List<Integer> totalUserList =new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);  //一天中的最小点
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);   //一天中的最大点

           Integer totalUserCount = userMapper.selectUserCount(endTime);
           totalUserCount= totalUserCount == null?0:totalUserCount;
           totalUserList.add(totalUserCount);

            Integer newuserCount = userMapper.selectNewCreateTime(beginTime,endTime);
            newuserCount= newuserCount == null?0:newuserCount;
            newUserList.add(newuserCount);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //每天有效订单 select count(id) from orders where statue=已完成 and order_time>? and order_time>?
        List<Integer> orderList = new ArrayList<>();
        //每天订数单总：select count(id) from orders where order_time>? and order_time>?
        List<Integer> allOrderList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //总订单
            Integer AllorderCount = getOrderCount(beginTime, endTime, null);

            //有效订单
            Integer orderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            allOrderList.add(AllorderCount);
            orderList.add(orderCount);

        }
        //计算时间区间内的订单总数量
        Integer totalOrderCount = allOrderList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单总数量
        Integer validOrderCount = orderList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double CompletionRate = 0.0;
        if (totalOrderCount!=0){
             CompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(allOrderList,","))
                .validOrderCountList(StringUtils.join(orderList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(CompletionRate)
                .build();
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end ,Integer status){
        Map map=new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.selectOrder(map);
    }


    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10ReportVO(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);  //一天中的最小点
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);   //一天中的最大点



            List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.GoodsSales(beginTime, endTime);

            List<String> names = goodsSalesDTOList.stream()
                    .map(GoodsSalesDTO::getName)
                    .collect(Collectors.toList());
            String nameList = StringUtils.join(names, ",");

            List<Integer> number = goodsSalesDTOList.stream()
                    .map(GoodsSalesDTO::getNumber)
                    .collect(Collectors.toList());
            String numberList = StringUtils.join(number, ",");



//            List<String> names =new ArrayList<>();
//            List<Integer> numbers =new ArrayList<>();
//
//            for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
//                String name = goodsSalesDTO.getName();
//                names.add(name);
//                Integer number = goodsSalesDTO.getNumber();
//                numbers.add(number);
//            }
//           String nameList = StringUtils.join(names, ",");
//           String numberList = StringUtils.join(numbers, ",");


            return SalesTop10ReportVO.builder()
                    .nameList(nameList)
                    .numberList(numberList)
                    .build();
        }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
     //1.查询数据库，获取运营数据（最近30天）
        LocalDate dateBegin = LocalDate.now().minusDays(30);//从今天往前到30天
        LocalDate dateEnd = LocalDate.now().minusDays(1); //昨天
     //查询概览数据
        BusinessDataVO businessDataVO = workSpaceSrevice.getbusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //2.通过POI，将数据写入excel文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模板文件创建一个新的excel文件
        XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);

        //填充数据
        //获取sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");

       //获取第二行的第二个单元格并填充
        sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);

       //获得第4行
        XSSFRow row = sheet.getRow(3);
        //第三个单元格
        row.getCell(2).setCellValue(businessDataVO.getTurnover());
        //第5个单元格
        row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDataVO.getNewUsers());


        //获得第五行
         row = sheet.getRow(4);
        //第三个单元格
        row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        //第五个单元格
        row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //填充明细数据
        for (int i=0;i<30;i++){
            LocalDate date = dateBegin.plusDays(i);
            //查询某一天的数据
            workSpaceSrevice.getbusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
            //获得某一行
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
        }

        //3.通过输出流，将excel文件下载到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        //关闭资源
        outputStream.close();
        excel.close();
    }
}
